Принцип підстановки Лісков (LSP)
📌 Що таке LSP?
Принцип підстановки Лісков (Liskov Substitution Principle) стверджує, що підкласи повинні коректно замінювати батьківські класи без порушення поведінки програми.
🛠 Приклад порушення LSP
Припустимо, що у нас є базовий клас Rectangle і підклас Square, який змінює поведінку.
public class Rectangle {
protected int width;
protected int height;
public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}
}
public class Square extends Rectangle {
@Override
public void setWidth(int width) {
this.width = width;
this.height = width; // Зміна поведінки!
}
@Override
public void setHeight(int height) {
this.width = height;
this.height = height; // Зміна поведінки!
}
}
✅ Виправлення LSP
Краще створити окремий інтерфейс для квадратів та прямокутників, щоб уникнути порушення LSP.
public interface Shape {
int getArea();
}
public class Rectangle implements Shape {
private int width;
private int height;
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getArea() {
return width * height;
}
}
public class Square implements Shape {
private int side;
public Square(int side) {
this.side = side;
}
public int getArea() {
return side * side;
}
}
Назад Далі